package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import dao.UserDao;
import dao.impl.UserDaoImpl;
import model.User;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		String action = (String) request.getParameter("action");
		try {
			if(action.equals("login")) {
				login(request,response);
			}else if(action.equals("register")) {
				register(request,response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	

	//登录方法
	private void login(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
		//得到前端页面表单中的信息
		String name = (String) request.getParameter("user");
		String pwd = (String) request.getParameter("pass");
		//创建数据访问对象
		UserDao ud = new UserDaoImpl();
		User user =ud.getUserByIdAndPwd(name, pwd);
		if(user != null) {
			HttpSession session = request.getSession();
			session.setAttribute("logoner", user);
			response.sendRedirect("IndexServlet");
		}else {
			response.sendRedirect("pages/logon.jsp");
		}
	}
	//注册方法
	private void register(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
		//得到前端页面的注册信息
		String id = request.getParameter("email");
		String name = request.getParameter("username");
		String sex = request.getParameter("sex");
		String pwd1 = request.getParameter("password");
		//创建数据访问对象
		UserDao ud = new UserDaoImpl();
		boolean user =  ud.register(id,name,sex,pwd1);
		if(user) {
			response.sendRedirect("pages/logon.jsp");
		}else {
			response.sendRedirect("pages/register.jsp");
		}
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
